package com.wuye.bpm;

import java.util.List;
import java.util.Map;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;

import com.wuye.common.util.StringUtil;
import com.wuye.entity.PageCond;

public class ProcessManager {

	private ProcessEngine processEngine;

	private final static ProcessManager INSTANCE = new ProcessManager();
	
	private ProcessManager() {
		processEngine = ProcessEngines.getDefaultProcessEngine();
	}

	public static ProcessManager getInstance() {
		return INSTANCE;
	}

	/**
	 * 列出所有流程模板
	 */
	public List<ProcessDefinition> listProcessDefinition(PageCond page) {
		ProcessDefinitionQuery defQry = processEngine.getRepositoryService().createProcessDefinitionQuery();
		return defQry.latestVersion().listPage(page.getBeginIndex(), page.getLength());
	}

	/**
	 * 部署流程
	 * 部署放到classes目录下的制定名称的流程
	 */
	public String deployProcess(String processName) {
		if (StringUtil.isEmpty(processName)) return null;
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		 RepositoryService repositoryService = processEngine.getRepositoryService();
		Deployment dm = repositoryService.createDeployment().addClasspathResource(processName).deploy();
		return dm.getId();
	}
	
	/**
	 * 获取流程
	 * @param processDefinitionId
	 * @return
	 */
	public ProcessDefinition getProcess(String processDefinitionId) {
		if (StringUtil.isEmpty(processDefinitionId)) return null;
		 RepositoryService repositoryService = ProcessEngines.getDefaultProcessEngine().getRepositoryService();
		//创建查询对象  
		    ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
		    //添加查询条件  
		    query.processDefinitionId(processDefinitionId)
		    //.processDefinitionKey("myProcess");//通过key获取  
		        // .processDefinitionName("My process")//通过name获取  
		        // .orderByProcessDefinitionId()//根据ID排序  
		    .latestVersion();
		    //执行查询获取流程定义明细  
		    List<ProcessDefinition> pds = query.list();
//		    for (ProcessDefinition pd : pds) {
//		        System.out.println("ID:"+pd.getId()+",NAME:"+pd.getName()+",KEY:"+pd.getKey()+",VERSION:"+pd.getVersion()+",RESOURCE_NAME:"+pd.getResourceName()+",DGRM_RESOURCE_NAME:"+pd.getDiagramResourceName());  
//		    }
		    if(null == pds || pds.size() == 0)
		    	return null;
		return pds.get(0);
	}


	/**
	 * 获取流程
	 * @param processDefinitionName
	 * @return
	 */
	public ProcessDefinition getProcessByProcessDefinitionName(String processDefinitionName) {
		if (StringUtil.isEmpty(processDefinitionName)) return null;
		 RepositoryService repositoryService = ProcessEngines.getDefaultProcessEngine().getRepositoryService();
		//创建查询对象  
		    ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
		    //添加查询条件  
		    query.processDefinitionName(processDefinitionName);
		    //执行查询获取流程定义明细  
		    List<ProcessDefinition> pds = query.list();
		    if(null == pds || pds.size() == 0)
		    	return null;
		return pds.get(0);
	}

	/**
	 * 启动一个流程实例
	 */
	public String startProcessInstanceById(String id) {
		RuntimeService service = ProcessEngines.getDefaultProcessEngine().getRuntimeService();
		ProcessInstance pi = service.startProcessInstanceById(id);
		return pi.getId();
	}


	/**
	 * 根据流程定义的名称启动一个流程实例
	 * @param processDefName
	 * @param businessKey
	 * @param variables
	 * @return
	 */
	public String startProcess(String processDefName, String businessKey, Map<String, Object> variables) {
		RuntimeService service = ProcessEngines.getDefaultProcessEngine().getRuntimeService();
		ProcessInstance pi = service.startProcessInstanceByKey(processDefName, businessKey, variables);
		return pi.getId();
	}
	
	/**
	 * 所有已启动流程实例
	 * @param page
	 * @return
	 */
	public List<ProcessInstance> listStartedProcessInstance(PageCond page) {
		RuntimeService service = ProcessEngines.getDefaultProcessEngine().getRuntimeService();
		List<ProcessInstance> list = service.createProcessInstanceQuery().listPage(page.getBeginIndex(), page.getLength());
		return list;
	}

	/**
	 * 查询某个人的任务列表
	 * @param mav
	 * @return
	 */
	public List<Task> listMyTask(String assignee, PageCond pc) {
		TaskService service = ProcessEngines.getDefaultProcessEngine().getTaskService();
		if(null == pc){
			return service.createTaskQuery().taskAssignee(assignee).list();
		}
		return service.createTaskQuery().taskAssignee(assignee).listPage(pc.getBeginIndex(), pc.getLength());
	}

	/**
	 * 完成一个制定任务
	 * @param id
	 */
	public void completeTask(String id) {
		ProcessEngines.getDefaultProcessEngine().getTaskService().complete(id);
	}

	/**
	 * 显示流程图
	 * @param definitionId
	 * @param instanceId
	 * @param taskId
	 * @param mav
	 * @param response
	 * @return 
	 * @throws IOException
	 */
//	public InputStream graphics(String definitionId, String instanceId, String taskId, ModelAndView mav, HttpServletResponse response) throws IOException {
//
//		Command<InputStream> cmd = null;
//
//		if (StringUtil.isNotNull(definitionId)) {
//			cmd = new GetDeploymentProcessDiagramCmd(definitionId);
//		}
//
//		if (StringUtil.isNotNull(instanceId)) {
//			cmd = new ProcessInstanceDiagramCmd(instanceId);
//		}
//
//		if (StringUtil.isNotNull(taskId)) {
//			Task task = ProcessEngines.getDefaultProcessEngine().getTaskService().createTaskQuery().taskId(taskId).singleResult();
//			cmd = new ProcessInstanceDiagramCmd(task.getProcessInstanceId());
//		}
//
//		if (cmd != null) {
//			return ProcessEngines.getDefaultProcessEngine().getManagementService().executeCommand(cmd);
//		}
//		return null;
//	}
}
